<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">











<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "9c84d93b"
    });
  daovoice('update');
  </script>












<link href="/personblog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/personblog/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/personblog/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/personblog/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/personblog/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/personblog/images/logo.svg?v=6.1.0" color="#222">







<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>


<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/personblog/',
    scheme: 'Muse',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="1.什么时候堆是JVM所管理的最大的一块内存空间，主要用于存放各种类的实例对象。JVM中的堆一般分为三个部分：新生代、老年代、永久代。 堆的内存模型 JVM中每次只会使用Eden区和其中一块survivor区域来为对象服务，所以无论什么时候总有一块survivor区域空闲着。因此新生代实际可用内存空间为90%的新生代空间。  新生代  主要用来存放新生的对象，一般占据堆得1/3空间。由于频繁创建对">
<meta name="keywords" content="java,GC,jvm">
<meta property="og:type" content="article">
<meta property="og:title" content="垃圾回收机制">
<meta property="og:url" content="http://zhangsnke.gitee.io/2018/04/28/1.什么时候/index.html">
<meta property="og:site_name" content="Zhangsnke&#39;s Blog">
<meta property="og:description" content="1.什么时候堆是JVM所管理的最大的一块内存空间，主要用于存放各种类的实例对象。JVM中的堆一般分为三个部分：新生代、老年代、永久代。 堆的内存模型 JVM中每次只会使用Eden区和其中一块survivor区域来为对象服务，所以无论什么时候总有一块survivor区域空闲着。因此新生代实际可用内存空间为90%的新生代空间。  新生代  主要用来存放新生的对象，一般占据堆得1/3空间。由于频繁创建对">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://s1.ax1x.com/2018/04/12/CAXclt.png">
<meta property="og:updated_time" content="2018-04-12T08:35:28.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="垃圾回收机制">
<meta name="twitter:description" content="1.什么时候堆是JVM所管理的最大的一块内存空间，主要用于存放各种类的实例对象。JVM中的堆一般分为三个部分：新生代、老年代、永久代。 堆的内存模型 JVM中每次只会使用Eden区和其中一块survivor区域来为对象服务，所以无论什么时候总有一块survivor区域空闲着。因此新生代实际可用内存空间为90%的新生代空间。  新生代  主要用来存放新生的对象，一般占据堆得1/3空间。由于频繁创建对">
<meta name="twitter:image" content="https://s1.ax1x.com/2018/04/12/CAXclt.png">






  <link rel="canonical" href="http://zhangsnke.gitee.io/2018/04/28/1.什么时候/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>垃圾回收机制 | Zhangsnke's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
<a href="https://github.com/zxk318www"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/personblog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhangsnke's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
          
  
  <li class="menu-item menu-item-home menu-item-active">
    <a href="/personblog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-about">
    <a href="/personblog/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-tags">
    <a href="/personblog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-categories">
    <a href="/personblog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-archives">
    <a href="/personblog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
</li>

      

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhangsnke.gitee.io/personblog/2018/04/28/1.什么时候/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zhangsnke">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://s1.ax1x.com/2018/04/04/C9BbPU.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhangsnke's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">垃圾回收机制</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-28T10:45:56+08:00">2018-04-28</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/personblog/categories/java基础知识/" itemprop="url" rel="index"><span itemprop="name">java基础知识</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="1-什么时候"><a href="#1-什么时候" class="headerlink" title="1.什么时候"></a><strong>1.什么时候</strong></h1><p>堆是JVM所管理的最大的一块内存空间，主要用于存放各种类的实例对象。JVM中的堆一般分为三个部分：<font color="red">新生代、老年代、永久代</font>。</p>
<p>堆的内存模型<br><img src="https://s1.ax1x.com/2018/04/12/CAXclt.png" alt="enter image description here"></p>
<p>JVM中每次只会使用Eden区和其中一块survivor区域来为对象服务，所以无论什么时候总有一块survivor区域空闲着。因此新生代实际可用内存空间为90%的新生代空间。</p>
<ol>
<li>新生代</li>
</ol>
<p>主要用来存放新生的对象，一般占据堆得1/3空间。由于频繁创建对象，索引新生代会频繁发出minor gc进行垃圾回收。新生代又被划为三个区：Eden区、from survivor、to survivor。<font color="blue">Eden区：</font>java新生对象的出生地(如果新创建的对象占用内存很大，则直接分配到来年代)。当Eden区内存不够的时候会触发minor gc，对新生代代区域进行一次垃圾回收。</p>
<p>Minor GC的过程：采用<font color="red">复制算法</font>，首先把Eden区和from survivor区域中存货的对象复制到to survivor区域，然后再把Eden区和from survivor区域清除。to survivor区域将这些存活的对象年龄+1（如果to survivor不够位置了就放到老年区）。以后对象在survivor区域中每熬过一次gc则年龄+1，当年龄到达某个值（默认为15），这些对象就会成为老年代。最后from survivor 和 to survivor互换，原to survivor成为下一次GC时的from survivor区。</p>
<ol start="2">
<li>老年代</li>
</ol>
<p>主要存放应用程序中生命周期长的内存对象，对于一些较大的对象（急需要分配一块较大的连续内存空间），是直接进入老年代的，还有一些是从新生代survivor区域熬过来的对象。</p>
<p>老年代的对象比较稳定，所以 full gc不会频繁执行，升到老年代的对象大于老年代剩余空间时full gc，或者小于时被HandlePromotionFailure参数强制full gc。</p>
<p>Full gc采用标记-清除算法：首先扫描一次所有的老年代，标记处存活对象，然后挥手没有被标记的对象。Full gc耗时长，因为要扫描再挥手，会产生内存碎片，为了减少内存损耗，可采用标记整理法。当老年代也装不下的时候，就会抛出OOM异常。</p>
<ol start="3">
<li>永久代</li>
</ol>
<p>指内存的永久保存区域，主要存放class和原数据信息。类在被加载的时候放入永久代。他和堆区域不一样，gc不会在主程序运行期间对永久代进行清理。这也导致了永久代的区域随着加载类的增多而胀满，最终抛出<font color="red">OOM异常（堆内存溢出）</font>。</p>
<p>java8中，永久代已经被移除，被一个称为“元空间”的区域所取代。元空间的本质和永久代类似，都是对jvm规范中方法区的实现。不过元空间和永久代的最大区别在于：<font color="blue">元空间不在jvm，而是使用本地内存。默认情况下，元空间的大小仅受本地内存限制。类的元数据放入本地内存，字符串池和静态变量放入java堆中。这样加载多少类的元数据是由系统的实际可用空间来控制的。</font></p>
<p>采用元空间取代永久代的原因：<br>A. 为了解决永久代OOM问题，元数据和类对象存放在永久代中，容易出现性能问题和内存溢出。<br>B. 类及方法的信息等比较难确定其大小，因此对于永久代的大小指定比较困难，太小容易出现永久代溢出，太大则容易导致老年代溢出（因此对控件有限，此消彼长）。</p>
<hr>
<h1 id="2-对什么对象"><a href="#2-对什么对象" class="headerlink" title="2.对什么对象"></a><strong>2.对什么对象</strong></h1><p>Java并不采用引用计数法来判定对象是否可用，因为引用计数法不能很好地解决循环引用问题。而是采用<font color="red">根搜索法</font>，思想是通过一系列名为“GC ROOTS”的对象作为起始点，从节点开始向下搜索，搜索所走过的路径称为引用链。当一个对象到GC ROOTS没有任何引用链相连，即从GC ROOTS到这个对象不可达。则证明此对象不可用，可回收。从root搜索不到，且经过第一次标记清理后，仍然没有复活的对象。</p>
<p>可作为GC ROOTS的对象：虚拟机栈中局部变量引用的对象。类静态属性引用的对象。常量引用的对象，<a href="https://baike.sogou.com/v585784.htm?fromTitle=JNI" target="_blank" rel="noopener">JNI</a>中引用的对象。</p>
<hr>
<h1 id="3-做了什么"><a href="#3-做了什么" class="headerlink" title="3.做了什么"></a><strong>3.做了什么</strong></h1><p>主要做了清理对象、整理内存的工作。新生代采用了复制算法，过程如上。复制算法<font color="red">优点：无内存碎片化</font>,<font color="blue">浪费可用内存</font>。老年代采用的是标记整理法，首先扫描一次所有老年代，标记处存活对象，然后把存活对象再移动到一端，最后回收没有被标记的对象。标记的过程其实就是遍历所有gc roots，然后将所有gc roots可到达的对象标记为存活对象。缺点：标记和整理过程效率不高，因为还需要移动对象，成本相对较高。优点：不会产生内存碎片化。</p>
<p>垃圾回收算法：</p>
<ol>
<li>标记清除法：先标记要回收的对象，再统一进行回收操作。简单方便、内存碎片化严重。</li>
<li>复制算法：将对分成2部分，一份空白（A），一份存放对象（B），GC后，将B中存活的对象复制到A中，然后B变成空白。</li>
<li>标记-整理：先标记可回收对象，将存活的对象移动到一端，再回收对象。无内存碎片。成本相对较高</li>
<li>分代回收：年轻代用复制算法，老年代用标记整理算法。</li>
</ol>
<p>根据对象存活特性，合理使用回收算法，商业jvm都用分代回收。</p>
<p>既然jvm采用分代回收，name年轻代和老年代各自使用的垃圾收集器也不一样。年轻代使用的垃圾收集器是：Serial，ParNew，Parallel Scavenge。老年代使用的是：CMS，SerialOld，Parallel Old。通用的收集器<a href="https://blog.csdn.net/zhanggang807/article/details/45956325" target="_blank" rel="noopener">G1</a>。</p>
<ol>
<li>串行的，也就是采用单线程（比较老了），分类：serial new（收集年轻代，复制算法）和serial old（收集老年代，标记整理），缺点：单线程，进行垃圾回收时暂时所有的用户线程。优点：实现简单。</li>
<li>并行的，采用多线程，对于年轻代有两个：ParNew和Parallel scavenge，ParNew回收期间暂停其他所有工作线程。parallel scavenge是一个针对年轻代的垃圾回收器，采用复制算法，主要的优点是进行垃圾回收时不会停止用户线程。Parallel Old是老年代的垃圾回收器，使用多线程，标记整理法。</li>
</ol>
<p>CMS收集器：已获得最短回收暂停时间为目标，允许垃圾收集线程与用户线程并行。主要有以下4个阶段：</p>
<ol>
<li>初始标记，标记GC ROOTS可关联的用户对象，会暂停用户线程。</li>
<li>并发标记，根搜索过程中，用户线程并行。</li>
<li>重新标记，由于在并发标记过程中，用户线程导致的对象状态变化，会暂停用户线程。</li>
<li>并清理，清理可回收对象，用户线程并行。</li>
</ol>
<p>G1：一款先进的通用垃圾收集器，他针对整个堆，并将其分为大小相等的区域，记录每个区占用信息，优先回收价值更高的区域。</p>

      
    </div>

    

    
    
    

<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fq7f9mgftqj30yf11x793.jpg" alt="Zhangsnke 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fq7f9yogljj30ox0qi76z.jpg" alt="Zhangsnke 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/personblog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/personblog/tags/GC/" rel="tag"><i class="fa fa-tag"></i> GC</a>
          
            <a href="/personblog/tags/jvm/" rel="tag"><i class="fa fa-tag"></i> jvm</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/personblog/2018/04/28/hello-world/" rel="next" title="Hello World">
                <i class="fa fa-chevron-left"></i> Hello World
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/personblog/2018/04/28/java1/" rel="prev" title="java中关于try、catch、finally的分析">
                java中关于try、catch、finally的分析 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="uyan_frame"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://s1.ax1x.com/2018/04/04/C9BbPU.jpg"
                alt="Zhangsnke" />
            
              <p class="site-author-name" itemprop="name">Zhangsnke</p>
              <p class="site-description motion-element" itemprop="description">java jsp</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/personblog/archives/">
                
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/personblog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/personblog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/zxk318www" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:1137824821@qq.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/u/3487862312" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-什么时候"><span class="nav-number">1.</span> <span class="nav-text">1.什么时候</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-对什么对象"><span class="nav-number">2.</span> <span class="nav-text">2.对什么对象</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-做了什么"><span class="nav-number">3.</span> <span class="nav-text">3.做了什么</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhangsnke</span>

  

  
</div>




<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>
  <!-- <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Muse</a> v6.1.0</div>
-->





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共字</span>
</div>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/personblog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/personblog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/personblog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/personblog/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/personblog/js/src/motion.js?v=6.1.0"></script>



  
  

  
  <script type="text/javascript" src="/personblog/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/personblog/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/personblog/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2161053"></script>
      <!-- UY END -->
    
  





  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/personblog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
</body>
</html>

